package cn.xuyun.cc.tcp;

import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;



import cn.xuyun.cc.tcp.util.LogUtil;
import cn.xuyun.cc.tcp.vo.Constants;
import cn.xuyun.cc.tcp.vo.Entity;



public class TcpServerHandler extends SimpleChannelUpstreamHandler {

	
	private static final Logger logger  = Logger.getLogger(TcpServerHandler.class);

	public static final ChannelGroup channels = new DefaultChannelGroup();
	
	static final ConcurrentHashMap<Integer, Integer> cmdMap=new ConcurrentHashMap<Integer, Integer>();
	
	static final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	
	
	
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
		
		Entity entity=(Entity)e.getMessage();
		
		if(entity.getCmd()==11111)
		{
			//设备注册
			logger.info("send to client 11111");
			int time=(int)(new Date().getTime()/1000);
			Entity ok=new Entity(time,1,0,1,2007,sdf.format(new Date()).getBytes());
			ByteArrayOutputStream bos=new ByteArrayOutputStream(); 
			try{
				bos.write("OK".getBytes());
				bos.write(0);
				bos.write(0);
				bos.write(0);
				bos.write(0);
				bos.write(ok.getBytes());
			}catch(Exception ex)
			{
				ex.printStackTrace();
			}
			Entity res=new Entity(time, 1, 0, 1, 11111, "OK".getBytes());
			e.getChannel().write(res);
		}
		else if(entity.getType()==1)
		{
			if(TelnetServerHandler.channel!=null)
			{
				TelnetServerHandler.channel.write(entity.toString());
			}
		}
		
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		e.getCause().printStackTrace();
		e.getChannel().close();
	}
}
